import datetime

from django.db.models.signals import m2m_changed, post_save, post_delete, pre_delete
from django.dispatch import receiver
from .models import Article, ArticleKeyword
# import logging
from logger.logger_handler import Logger
logger = Logger(logger='signals.py').get_logger()

# logging.basicConfig(level=logging.DEBUG, filename="signal.log")
# logger = logging.getLogger()

"""
    文章删除更新、修改关键词信息时同步更改关键词统计次数
    https://docs.djangoproject.com/zh-hans/4.2/ref/signals/
"""

"""
    @action :    update   |   delete
"""


def update_article_keyword_value(instance, action="update"):
    keywords = instance.keywords.all()
    for keyword in keywords:
        if action == "update":
            keyword.value = keyword.article_set.count()
            logger.debug(f"更新关键词 {keyword.text} 次数：{keyword.value}")
        else:
            keyword.value = max(keyword.article_set.count() - 1, 0)
            logger.debug(f"{keyword.text} 次数 - 1：{keyword.value}")
        keyword.save()


# 仅文章关键词修改会触发
@receiver(m2m_changed, sender=Article.keywords.through)
def update_article_keywords_count(sender, instance, action, reverse, model, pk_set, **kwargs):
    logger.debug(f"=========== update_article_keywords_count begin {datetime.datetime.now()} ==================\n")

    if action in ['post_add', 'post_remove', 'post_clear']:
        for pk in pk_set:
            keyword_instance = ArticleKeyword.objects.get(id=pk)
            keyword_instance.value = keyword_instance.article_set.count()
            keyword_instance.save()
        update_article_keyword_value(instance)

    logger.debug("=========== update_article_keywords_count end ==================\n")


# 仅新增文章会触发
@receiver(post_save, sender=Article)
def update_or_add_article(sender, instance, created, **kwargs):
    logger.debug("============== update_or_add_article begin ================\n")
    if created:
        update_article_keyword_value(instance)
    logger.debug("============== update_or_add_article end ================\n")


# 仅文章删除会触发，使用 post_save 会导致 无法获取 m2m 内容，为None
@receiver(pre_delete, sender=Article)
def before_deleted_article(sender, instance, **kwargs):
    logger.debug("after_deleted_article\n")
    update_article_keyword_value(instance, "delete")
